#include "mysql_connection_pool.h"
#include "utils.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <mysql/mysql.h>

MySQLConnectionPool::MySQLConnectionPool(const std::string& host, const std::string& user,
                                         const std::string& password, const std::string& db,
                                         int max_conn)
    : max_connections(max_conn) {
    for (int i = 0; i < max_connections; ++i) {
        MYSQL* conn = mysql_init(nullptr);
        if (!conn) {
            handleError(nullptr, "mysql_init() failed");
        }
        if (!mysql_real_connect(conn, host.c_str(), user.c_str(),
                                password.c_str(), db.c_str(), 0, nullptr, 0)) {
            handleError(conn, "mysql_real_connect() failed");
        }
        pool.push_back(conn);
    }
}

MYSQL* MySQLConnectionPool::getConnection() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [this] { return !pool.empty(); });
    MYSQL* conn = pool.back();
    pool.pop_back();
    return conn;
}

void MySQLConnectionPool::releaseConnection(MYSQL* conn) {
    std::lock_guard<std::mutex> lock(mtx);
    pool.push_back(conn);
    cv.notify_one();
}

MySQLConnectionPool::~MySQLConnectionPool() {
    for (auto conn : pool) {
        mysql_close(conn);
    }
}